﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CodeDynamiksEngine;

using MESCodeFile;

namespace mes_tublay
{
    public partial class frmDocumentsCheckList : Form
    {
        CodeScript script;
        CodeProcessor proc = new CodeProcessor(ThreadingMode.Normal);
        DataCache dat = new DataCache("myData");
        DataCache cache = new DataCache("Data");

        string[] metaData = new string[0];
        string applicationNumber, referenceNumber, businessReferenceNumber;
        bool isNotify = false;

        int userToEdit = -1;
        bool isEditingMode = false;
        string status = "";
        updateInfo appInfo = new updateInfo();

        string department="";
        string office = "";

        //constructors
        public frmDocumentsCheckList(string dept)
        {
            department = dept;
            InitializeComponent();
            InitializeFrameSliderForm();
        }
        //for live notification
        public frmDocumentsCheckList(string dept, bool status)
        {
            department = dept;
            isNotify = status;

            InitializeComponent();
            InitializeFrameSliderForm();
        }

        public frmDocumentsCheckList()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
            
        }

        private void InitializeForm()
        {
            proc.ProcessCompleted += new EventHandler(proc_ProcessCompleted);
            lstApplicationNumber.DoubleClick += new EventHandler(lstApplicationNumber_DoubleClick);
            txtSearch.KeyPress += new KeyPressEventHandler(txtSearch_KeyPress);
            btnCancel.Click += new EventHandler(btnCancel_Click);
            btnBreakdownFeesAndCharges.Click += new EventHandler(btnBreakdownFeesAndCharges_Click);

            txtResponsibleOffice.SelectedIndexChanged += new EventHandler(txtResponsibleOffice_SelectedIndexChanged);
            lblDepartment.Text = department;

            approved.Click += new EventHandler(approved_Click);
            disapproved.Click += new EventHandler(disapproved_Click);
            pending.Click += new EventHandler(pending_Click);

            if (!isNotify)
                loadApplicationNumber();
            else
                LoadInformation();
        }

        void pending_Click(object sender, EventArgs e)
        {
            status = "PENDING";
            saveInfo();
        }

        void disapproved_Click(object sender, EventArgs e)
        {
            status = "DISAPPROVED";
            saveInfo();
        }

        void approved_Click(object sender, EventArgs e)
        {
            status = "APPROVED";
            saveInfo();
        }

        //double click an application number from the list
        void lstApplicationNumber_DoubleClick(object sender, EventArgs e)
        {
            if (!isNotify)
            {
                //disable search panel
                grpSearch.Enabled = false;
                grpData.Enabled = true;

                //When the user double clicks the user profile, load the profile
                if (lstApplicationNumber.SelectedIndices.Count == 0) return;
                dat.SetActivePage(0);
                userToEdit = lstApplicationNumber.SelectedIndices[0];

                //display the application number
                txtApplicationNumber.Text = dat.GetValue(userToEdit, "fApplicationNumber").ToString();
                //display company Name or Fullname
                if (dat.GetValue(userToEdit, "ffLastName").ToString() == "") txtName.Text = dat.GetValue(userToEdit, "ffCompanyName").ToString();
                else txtName.Text = dat.GetValue(userToEdit, "ffLastName").ToString() + "," + dat.GetValue(userToEdit, "ffFirstName").ToString() + " " + dat.GetValue(userToEdit, "ffMiddleName").ToString();

                if (!department.Equals("for Other Offices"))
                    LoadAppData();
            }
        }
        //select responsible office
        void txtResponsibleOffice_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (txtResponsibleOffice.Text.Equals("BARANGAY"))
            {
                search();
            }
        }
       
        void btnBreakdownFeesAndCharges_Click(object sender, EventArgs e)
        {
            frmBreakdown frm = new frmBreakdown(this, txtApplicationNumber.Text, txtResponsibleOffice.Text, txtDate.Value.ToString("yyyy-MM-dd"));
            frm.ShowDialog();
        }
        
        void btnCancel_Click(object sender, EventArgs e)
        {
            txtApplicationNumber.Text = "";
            txtDescription.Text = "";
            txtIssuedBy.Text = "";
            txtName.Text = "";
            txtRemarks.Text = "";
            txtResponsibleOffice.Text = "";

            txtTotalFeesAndCharges.Value = 0;
            lblResult.Text = "...";
            isEditingMode = false;
            //chkApproved.Checked = false;
            grpSearch.Enabled = true;
            grpData.Enabled = false;
        }

        void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
        {
            loadApplicationNumber();
        }

        void checkOffice()
        {
            switch (department)
            {
                case "MUNICIPAL HEALTH OFFICE": office = "MHO"; break;
                case "MUNICIPAL ENGINEERING OFFICE": office = "MEO"; break;
                case "FIRE DEPARTMENT": office = "FIRE_DEPARTMENT"; break;
                case "MUNICIPAL PLANNING AND DEVELOPMENT OFFICE": office = "MPDO"; break;
                case "MASSO": office = "MASSO"; break;
                case "PNP_TUBLAY": office = "PNP_TUBLAY"; break;
            }
        }
        //entry point
        public void insertTotalValue(string val)
        {
            txtTotalFeesAndCharges.Text = val;
        }

        #region Methods for loading without the notification
            //method for committing 
            void saveInfo()
        {
            if (txtTotalFeesAndCharges.Text != "" && txtDescription.Text != "" && txtIssuedBy.Text != "" && txtRemarks.Text != "")
            {
                DialogResult result = Confirm.Question("Save Information", "Please double check your entries before saving.\r\n" +
                   "Do you wish to continue saving?");

                if (result == System.Windows.Forms.DialogResult.No) return;
                commit();
            }
            else
            {
                Confirm.Info("Information", "Please Fill-up All Required Fields");
            }
        }
            //method for getting application number with status equal to pending
            void loadApplicationNumber()
        {
            //Check if the processor is executing script, if it is, return to the calling code.
            if (proc.State != ProcessorFlag.Ready && proc.State != ProcessorFlag.DataRdy) return;

            script = new CodeScript("LOAD");
            script.Add(CodeIns.SYS_RESET);
            script.Add(CodeIns.DBU_NEW_CORE);
            script.Add(CodeIns.DBU_CONNECT, Common.CFG.Read("DRIVER"), Common.CFG.Read("DB"),
                       Common.CFG.Read("UID"), Common.CFG.Read("PWD"), Common.CFG.Read("SERVER"));
            script.Add(CodeIns.DBU_BEGIN_TRANSACTION);

            script.Add(CodeIns.DBU_QUERY, "SELECT fID, fStamp, fApplicationNumber, t1.fReferenceNumber, ffLastName, ffFirstName, ffMiddleName, ffCompanyName FROM tblBusinessInformation t1," +
                " (SELECT fReferenceNumber, fLastName AS ffLastName, fFirstName AS ffFirstName, fMiddleName AS ffMiddleName, fCompanyName AS ffCompanyName FROM tblBusinessOwnerProfile) AS t2 " +
                " WHERE (t1.fReferenceNumber = t2.fReferenceNumber) AND (fBusinessStatus = 'PENDING') AND ((ffLastName LIKE '%" + txtSearch.Text + "%') OR (ffFirstName LIKE '%" + txtSearch.Text + "%') OR (ffMiddleName LIKE '%" + txtSearch.Text + "%')" +
                                                    " OR (ffCompanyName LIKE '%" + txtSearch.Text + "%') OR (fApplicationNumber LIKE '%" + txtSearch.Text + "%')) ORDER BY fStamp DESC");
            if (department.Equals("for Other Offices"))
            {
                disapproved.Enabled = false;
                pending.Enabled = false;
                btnBreakdownFeesAndCharges.Enabled = false;
                script.Add(CodeIns.DBU_QUERY, "SELECT fData FROM tbllookup WHERE (fKey = 'DEPARTMENT' AND fData = 'BARANGAY') OR (fKey = 'DEPARTMENT' AND fData = 'OTHERS') ORDER BY fData ASC");
            }
            else
            {
                script.Add(CodeIns.DBU_QUERY, "SELECT fData FROM tbllookup WHERE fKey = 'DEPARTMENT' ORDER BY fData ASC");
            }
            script.Add(CodeIns.DBU_END);
            proc.Run(script);
        }
            //Load the application data from the database
            void LoadAppData()
            {
                checkOffice();
                CodeScript s = new CodeScript("GETAPPDATA");
                s.Add(CodeIns.SYS_USE_CORE, 0);
                s.Add(CodeIns.DBU_CONNECT, Common.CFG.Read("DRIVER"), Common.CFG.Read("DB"),
                        Common.CFG.Read("UID"), Common.CFG.Read("PWD"), Common.CFG.Read("SERVER"));

                s.Add(CodeIns.DBU_QUERY, "SELECT * FROM tblDocumentschecklist WHERE fApplicationNumber=" + Sym.PQS(dat.GetValue(userToEdit, "fApplicationNumber").ToString()) + " AND fResponsibleOffice = '" + department + "'");
                s.Add(CodeIns.DBU_QUERY, "SELECT SUM(fFee) FROM tblBusinessPermitFeesAndCharges WHERE fApplicationNumber=" + Sym.PQS(dat.GetValue(userToEdit, "fApplicationNumber").ToString()) + " AND fDepartment = '" + department + "'");
                //PREPARATION IN CASE ONE USER NEED TO INPUT ALL DEPARTMENT FEE
                s.Add(CodeIns.DBU_QUERY, "SELECT fData FROM tbllookup WHERE fKey = 'DEPARTMENT' ORDER BY fData ASC");
                s.Add(CodeIns.DBU_END);

                proc.Run(s);
            }
            //Fetch the Application Number List and Responsible Office
            void FetchData()
        {
            //Obtain the Application Number.
            dat.SetActivePage(0);

            //Add Application Number to ListView control
            lstApplicationNumber.Clear();
            object[] _AppNum = dat.GetObjectList("fApplicationNumber");
            object[] _info = dat.GetObjectList("ffLastName");
            object[] _cInfo = dat.GetObjectList("ffCompanyName");
            for (int i = 0; i < _AppNum.Length; i++)
            {
                if (_info[i].ToString() != "")
                    lstApplicationNumber.Items.Add(_AppNum[i].ToString() + "-" + _info[i].ToString(), 1);
                else
                    lstApplicationNumber.Items.Add(_AppNum[i].ToString() + "-" + _cInfo[i].ToString(), 1);
            }

            dat.SetActivePage(1);
            txtResponsibleOffice.Items.Clear();
            txtResponsibleOffice.Items.AddRange(dat.GetStringList(0));

        }
            //search if existing department approved documents 
            void search()
            {
                CodeScript s = new CodeScript("SEARCHDUPLICATE");
                s.Add(CodeIns.SYS_USE_CORE, 0);
                s.Add(CodeIns.DBU_CONNECT, Common.CFG.Read("DRIVER"), Common.CFG.Read("DB"),
                        Common.CFG.Read("UID"), Common.CFG.Read("PWD"), Common.CFG.Read("SERVER"));
                s.Add(CodeIns.DBU_QUERY, "SELECT * FROM tblDocumentschecklist WHERE fApplicationNumber=" + Sym.PQS(dat.GetValue(userToEdit, "fApplicationNumber").ToString()) + " AND fResponsibleOffice = '" + txtResponsibleOffice.Text + "' AND fStatus = 'APPROVED'");
                s.Add(CodeIns.DBU_END);
                proc.Run(s);
            }
            //commit information
            void commit()
            {
                CodeScript s = new CodeScript("COMMIT");
                s.Add(CodeIns.SYS_USE_CORE, 0);
                s.Add(CodeIns.DBU_CONNECT, Common.CFG.Read("DRIVER"), Common.CFG.Read("DB"),
                        Common.CFG.Read("UID"), Common.CFG.Read("PWD"), Common.CFG.Read("SERVER"));
                if (!isEditingMode)
                {
                    s.Add(CodeIns.DBU_INSERT, "tbldocumentschecklist", new string[] { "fApplicationNumber", "fDescription", "fResponsibleOffice", "fDateIssued", "fIssuedBy", "fOtherRemarks", "fStatus" },
                         new object[] { "'"+txtApplicationNumber.Text+"'", "'"+txtDescription.Text+"'", "'"+txtResponsibleOffice.Text+"'",
                         "'"+txtDate.Value.ToString("yyyy-MM-dd")+"'", "'"+txtIssuedBy.Text.Trim()+"'", "'"+txtRemarks.Text.Trim()+"'", "'"+status+"'"
                         });
                }
                else
                {
                    s.Add(CodeIns.DBU_UPDATE, "tbldocumentschecklist",
                   new string[]
                    {
                        "fDateIssued",
                        "fIssuedBy",
                        "fOtherRemarks",
                        "fStatus"
                    },
                   new object[]
                    {
                        "'" + txtDate.Value.ToString("yyyy-MM-dd")+ "'",
                        "'" + txtIssuedBy.Text.Trim() + "'",
                        "'" + txtRemarks.Text.Trim() + "'",
                        "'" + status + "'"
                    }, "fID='" + appInfo.fID + "' AND fStamp ='" + appInfo.fStamp.ToString("yyyy-MM-dd HH:mm:ss") + "'");
                }

                s.Add(CodeIns.DBU_END);

                proc.Run(s);
            }
        #endregion

        #region Methods for Loading Notification
            public void getApplication(string app, string refNo, string businessRefNo)
        {
            applicationNumber = app;
            referenceNumber = refNo;
            businessReferenceNumber = businessRefNo;

            metaData = new string[3];
            metaData[0] = app;
            metaData[1] = refNo;
            metaData[2] = businessRefNo;
        }
            void LoadInformation()
            {
                checkOffice();
                CodeScript s = new CodeScript("LOADDATA");
                s.Add(CodeIns.SYS_RESET, 0);
                s.Add(CodeIns.DBU_NEW_CORE);
                s.Add(CodeIns.DBU_CONNECT, Common.CFG.Read("DRIVER"), Common.CFG.Read("DB"),
                        Common.CFG.Read("UID"), Common.CFG.Read("PWD"), Common.CFG.Read("SERVER"));

                s.Add(CodeIns.DBU_QUERY, "SELECT * FROM tblDocumentschecklist WHERE fApplicationNumber='" + applicationNumber + "' AND fResponsibleOffice = '" + department+ "' ORDER BY fStamp ASC");//LIMIT 1,1 ");
                s.Add(CodeIns.DBU_QUERY, "SELECT fLastName, fFirstName, fMiddleName, fCompanyName FROM tblBusinessOwnerProfile " +
                    " WHERE fReferenceNumber = '" + referenceNumber + "'");
                s.Add(CodeIns.DBU_QUERY, "SELECT SUM(fFee) FROM tblBusinessPermitFeesAndCharges WHERE fApplicationNumber=" + applicationNumber + " AND fDepartment = '" + department + "'");
                s.Add(CodeIns.DBU_QUERY, "SELECT fData FROM tbllookup WHERE fKey = 'DEPARTMENT' AND fData = '"+department+"'");
                s.Add(CodeIns.DBU_END);

                proc.Run(s);
            }
        #endregion

        //processor
        void proc_ProcessCompleted(object sender, EventArgs e)
        {
            proc.SafeCall(this, delegate
            {
                if (proc.State == ProcessorFlag.Error ||
                    proc.State == ProcessorFlag.DataRdyErr ||
                    proc.State == ProcessorFlag.ReadyErr)
                {
                    MessageBox.Show(proc.GetProcessorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    proc.ClearErrorFlag();
                    return;
                }
                switch (proc.GetLastProcessName().ToString())
                {
                    case "SEARCHDUPLICATE":
                        DataCache check = new DataCache("myData");
                        proc.DataFetch(out check);
                        check.SetActivePage(0);
                        if (check.GetRecordCount(0) > 0)
                        {
                            MessageBox.Show("Duplicate Record Found", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            switch (txtResponsibleOffice.Text)
                            {
                                
                                default:
                                    //btnCommit.Enabled = true;
                                    //chkApproved.Enabled = false;
                                    //chkApproved.Checked = true;
                                    btnBreakdownFeesAndCharges.Enabled = false;
                                    break;
                            }
                        }

                        break;
                    case "COMMIT":
                        Confirm.Info("Save Information", "1 Record has been saved.");
                        if(!department.Equals("for Other Offices"))
                        Common.NOTIFY.Push("MAYOR_OFFICE", department + " - Reply on Business Permit Application: " + txtApplicationNumber.Text, new string[] { "" + txtApplicationNumber.Text, referenceNumber, businessReferenceNumber, department });
                        btnClose_Click(null, null);
                        break;

                    case "LOADDATA":
                        proc.DataFetch(out cache);
                        cache.SetActivePage(0);
                        int cnt = cache.GetRecordCount(0) ;
                        if (isNotify) grpData.Enabled = true;
                        //check if there is existing record on the tableDocumentsCheckList
                        if (cnt > 0)
                        {
                            isEditingMode = false;
                            txtApplicationNumber.Text = cache.GetValue(0, "fApplicationNumber").ToString();
                            txtIssuedBy.Text = cache.GetValue(0, "fIssuedBy").ToString();
                            txtRemarks.Text = cache.GetValue(0, "fOtherRemarks").ToString();

                            for (int i = 0; i < cache.GetRecordCount(0); i++)
                            {
                                string status = cache.GetValue(i, "fStatus").ToString();
                                switch (status)
                                {
                                    case "APPROVED": 
                                        approved.Enabled = false;
                                        disapproved.Enabled = false;
                                        pending.Enabled = false;
                                        btnCancel.Enabled = false;
                                        btnBreakdownFeesAndCharges.Enabled = false;
                                        lblResult.Text = "This application has been approved.";
                                        break;
                                    case "DISAPPROVED": 
                                        disapproved.Enabled = false;
                                        btnCancel.Enabled = false;
                                        btnBreakdownFeesAndCharges.Enabled = true;
                                        lblResult.Text = "This application has been disapproved.";
                                        break;
                                    case "PENDING": 
                                        pending.Enabled = false;
                                        btnCancel.Enabled = false;
                                        btnBreakdownFeesAndCharges.Enabled = true;
                                        lblResult.Text = "This application is pending for some reason.";
                                        break;
                                }
                            }
                            
                            
                            appInfo.fID = cache.GetValue(0, "fID").ToString();
                            appInfo.fStamp = DateTime.Parse(cache.GetValue(0, "fStamp").ToString());
                        }
                        // if no record
                        else
                        {
                            isEditingMode = false;
                            txtApplicationNumber.Text = applicationNumber;
                            approved.Enabled = true;
                            disapproved.Enabled = true;
                            pending.Enabled = true;
                            btnBreakdownFeesAndCharges.Enabled = true;
                            //btnCancel.Enabled = true;
                        }

                        //display basic information
                        cache.SetActivePage(1);
                        //display company Name or Fullname
                        if (cache.GetValue(0, "fLastName").ToString() == "") txtName.Text = cache.GetValue(0, "fCompanyName").ToString();
                        else txtName.Text = cache.GetValue(0, "fLastName").ToString() + "," + cache.GetValue(0, "fFirstName").ToString() + " " + cache.GetValue(0, "fMiddleName").ToString();

                        documentChecklist.responsibleOffice = department;
                        lblDepartment.Text = department;

                        txtDescription.Text = documentChecklist.description;
                        txtResponsibleOffice.Text = documentChecklist.responsibleOffice;
                        grpSearch.Enabled = false;

                        //obtain get summation
                        cache.SetActivePage(2);
                        decimal value = 0;
                        decimal.TryParse(cache.GetValue(0, 0).ToString(), out value);
                        txtTotalFeesAndCharges.Value = value;

                        //enable dropdownlist
                        cache.SetActivePage(3);
                        txtResponsibleOffice.Items.Clear();
                        txtResponsibleOffice.Items.AddRange(cache.GetObjectList(0));
                        txtResponsibleOffice.SelectedIndex = 0;
                        txtResponsibleOffice.Enabled = false;
                        
                        
                        break;
                    case "GETAPPDATA":
                        proc.DataFetch(out cache);
                        cache.SetActivePage(0);

                        cnt = cache.GetRecordCount(0) ;
                        
                        //check if there is existing record on the tableDocumentsCheckList
                        if (cnt > 0)
                        {
                            isEditingMode = false;
                            txtApplicationNumber.Text = cache.GetValue(0, "fApplicationNumber").ToString();
                            txtIssuedBy.Text = cache.GetValue(0, "fIssuedBy").ToString();
                            txtRemarks.Text = cache.GetValue(0, "fOtherRemarks").ToString();

                            for (int i = 0; i < cache.GetRecordCount(0); i++)
                            {
                                string status = cache.GetValue(i, "fStatus").ToString();
                                switch (status)
                                {
                                    case "APPROVED":
                                        approved.Enabled = false;
                                        disapproved.Enabled = false;
                                        pending.Enabled = false;
                                       // btnCancel.Enabled = false;
                                        btnBreakdownFeesAndCharges.Enabled = false;
                                        lblResult.Text = "This application has been approved.";
                                        break;
                                    case "DISAPPROVED":
                                        disapproved.Enabled = false;
                                       // btnCancel.Enabled = false;
                                        btnBreakdownFeesAndCharges.Enabled = true;
                                        lblResult.Text = "This application has been disapproved.";
                                        break;
                                    case "PENDING":
                                        pending.Enabled = false;
                                       // btnCancel.Enabled = false;
                                        btnBreakdownFeesAndCharges.Enabled = true;
                                        lblResult.Text = "This application is pending for some reason.";
                                        break;
                                }
                            }
                            
                            
                            appInfo.fID = cache.GetValue(0, "fID").ToString();
                            appInfo.fStamp = DateTime.Parse(cache.GetValue(0, "fStamp").ToString());
                        }
                        // if no record
                        else
                        {
                            isEditingMode = false;
                            //txtApplicationNumber.Text = applicationNumber;
                            approved.Enabled = true;
                            disapproved.Enabled = true;
                            pending.Enabled = true;
                            btnBreakdownFeesAndCharges.Enabled = true;
                            
                        }

                        //display basic information
                        txtDescription.Text = documentChecklist.description;
                        txtResponsibleOffice.Text = documentChecklist.responsibleOffice;
                        grpSearch.Enabled = false;

                        //obtain get summation
                        cache.SetActivePage(1);
                        value = 0;
                        decimal.TryParse(cache.GetValue(0, 0).ToString(), out value);
                        txtTotalFeesAndCharges.Value = value;

                        //enable dropdownlist
                        cache.SetActivePage(2);
                        txtResponsibleOffice.Items.Clear();
                        txtResponsibleOffice.Items.AddRange(cache.GetObjectList(0));
                        txtResponsibleOffice.SelectedItem = department;
                        txtResponsibleOffice.Enabled = false;
                        btnCancel.Enabled = true;

                        break;

                    case "LOAD":
                        proc.DataFetch(out dat);
                        FetchData();
                        break;
                }
            });
        }

    }
}
